//
// Copyright 2023 The Sparrow Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#ifndef SPARROW_COMMON_H_
#define SPARROW_COMMON_H_

#include <string>

#include "sparrow/impl/types.h"
#include "sparrow/impl/file.h"

namespace sparrow {
class FlexibleArrayHelper final {

public:
    FlexibleArrayHelper(struct FlexibleArray *p)
        : impl_(p) {}

    ~FlexibleArrayHelper() {
        if (impl_) FlexibleArrayFree(impl_);
    }

    FlexibleArrayHelper(const FlexibleArrayHelper &) = delete;
    FlexibleArrayHelper &operator=(const FlexibleArrayHelper &) = delete;

    std::string to_string() const {
        if (impl_) {
            return std::string(&impl_->data[0], impl_->length);
        }
        return std::string();
    }

    operator std::string() const { return to_string(); }

private:
    struct FlexibleArray *impl_;
};

class FileHandleGuard final {
public:
    explicit FileHandleGuard(sp_handle_t fd)
        : fd_(fd) {}
    ~FileHandleGuard() { spf_close(fd_); }
    FileHandleGuard(const FileHandleGuard &) = delete;
    FileHandleGuard &operator=(const FileHandleGuard &) = delete;
    sp_handle_t get() const { return fd_; }
    operator sp_handle_t() { return fd_; }

private:
    sp_handle_t fd_;
};
} // namespace sparrow

#endif // SPARROW_COMMON_H_
